package com.power.service.impl;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.power.constant.Constant;
import com.power.manager.RedisManager;
import com.power.mapper.TPermissionMapper;
import com.power.mapper.TRoleMapper;
import com.power.mapper.TUserMapper;
import com.power.model.TPermission;
import com.power.model.TRole;
import com.power.model.TUser;
import com.power.query.BaseQuery;
import com.power.query.UserQuery;
import com.power.service.UserService;
import com.power.util.CacheUtils;
import com.power.util.LoginInfoUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private TPermissionMapper tPermissionMapper;
    @Resource
    private TRoleMapper tRoleMapper;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private RedisManager redisManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if (tUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<TPermission> buttonPermissionList = tPermissionMapper.selectButtonPermissionByUserId(tUser.getId());
        tUser.setTPermissionList(buttonPermissionList);
        List<TRole> tRoles = tRoleMapper.selectByUserId(tUser.getId());
        tUser.setTRoles(tRoles);
        List<TPermission> menuPermissionList = tPermissionMapper.selectMenuPermissionByUserId(tUser.getId());
        tUser.setMenuPermissionList(menuPermissionList);
        return tUser;
    }

    @Override
    public PageInfo<TUser> getUserByPage(Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<TUser> tUsers = tUserMapper.selectUserByPage(BaseQuery.builder().build());
        PageInfo<TUser> pageInfo = new PageInfo<>(tUsers);
        return pageInfo;
    }

    @Override
    public TUser selectUserById(Integer id) {
        return tUserMapper.selectDetailById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveUser(UserQuery userQuery) {
        TUser tUser = new TUser();
        //spring提供的工具类，把userQuery的属性，拷贝到tUser中
        //两个对象的属性名和属性类型都要相同，才能赋值
        BeanUtils.copyProperties(userQuery, tUser);
        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        tUser.setCreateBy(LoginInfoUtil.getCurrentLoginUser().getId());
        tUser.setCreateTime(new Date());
        return tUserMapper.insertSelective(tUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editUser(UserQuery userQuery) {
        TUser tUser = new TUser();
        BeanUtils.copyProperties(userQuery, tUser);
        tUser.setEditBy(LoginInfoUtil.getCurrentLoginUser().getId());
        tUser.setEditTime(new Date());
        tUser.setLoginPwd(null);//更新用户不允许更新密码
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteUser(Integer id) {
        return tUserMapper.deleteByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchDelUserIds(List<String> idList) {
        return tUserMapper.batchDelUserIds(idList);
    }

    @Override
    public List<TUser> getOwnerList() {
        return CacheUtils.getCacheData(() -> {
            List<TUser> list = JSONUtil.toList(redisManager.getValue(Constant.REDIS_OWNER_KEY), TUser.class);
            return list;
        }, () -> {
            List<TUser> ownerList = tUserMapper.getOwnerList();
            return ownerList;
        }, (userList) -> {
            redisManager.setValue(Constant.REDIS_OWNER_KEY, JSONUtil.toJsonStr(userList));
        });

    }
}
